package com.netflexitysolutions.amazonws.ec2.internal.operations;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.amazonaws.ec2.doc._2009_04_04.DescribeInstancesInfoType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeInstancesItemType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeInstancesResponseType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeInstancesType;
import com.amazonaws.ec2.doc._2009_04_04.ReservationInfoType;
import com.netflexitysolutions.amazonws.ec2.RunningInstance;
import com.netflexitysolutions.amazonws.ec2.internal.ModelUtil;

public class ExperimantalDescribeInstancesOperation extends ExperimantalOperationExecutor<DescribeInstancesType, DescribeInstancesResponseType, List<RunningInstance>> {
	
	Set<String> objectIds;
	
	public ExperimantalDescribeInstancesOperation(Object ec2, Set<String> instanceIds) {
		super(ec2);
		objectIds = instanceIds;
//		if (objectIds == null || objectIds.size() == 0) {
//			throw new IllegalArgumentException("At least one instance id should be specified");
//		}
	}

	@Override
	protected void configureRestRequest(Map<String, String> request) {
		Iterator<String> iterator = objectIds.iterator();
		for (int i=0 ; i<objectIds.size(); i++) {
			request.put("InstanceId."+(i+1), iterator.next());
		}
	}

	@Override
	protected void configureSoapRequest(DescribeInstancesType request) {
		DescribeInstancesInfoType info = new DescribeInstancesInfoType();
		List<DescribeInstancesItemType> list = info.getItem();
		for (String instanceId : objectIds) {
			DescribeInstancesItemType item = new DescribeInstancesItemType();
			item.setInstanceId(instanceId);
			list.add(item);
		}
		request.setInstancesSet(info);
	}

	@Override
	protected String getEC2MethodName() {
		return "DescribeInstances";
	}

	@Override
	protected List<RunningInstance> processEC2Responce(
			DescribeInstancesResponseType response) {
		if (response.getReservationSet() == null) {
			return null;
		}
		List<RunningInstance> result = new ArrayList<RunningInstance>();
		List<ReservationInfoType> responseList = response.getReservationSet().getItem();
		for (ReservationInfoType reservationInfoType : responseList) {
			List<RunningInstance> tmp = ModelUtil.toDomainType(reservationInfoType);
			if (tmp != null) {
				result.addAll(ModelUtil.toDomainType(reservationInfoType));
			}
		}
		return result;
	}

}
